<template>
  <div class="search-table-style">
    <el-input
      @change="onChangeInput"
      v-model="value"
      placeholder="请选择"
      :suffix-icon="isShowTable ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
      @click.native="deptogglePanel($event)"
      size="mini"
      clearable
      :style="inputStyle"
    ></el-input>
    <div
      class="search-table"
      v-if="isShowTable"
      :style="tableStyle"
      ref="portTableRef"
    >
      <div class="head">
        <div class="select" v-if="isShowSelection">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="allChecked"
            @change="handleCheckAllChange"
            style="line-height: 35px"
          ></el-checkbox>
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="checkedList"
            @change="handleCheckedPortChange"
            class="check-group"
          >
            <el-checkbox
              v-for="(select, s) in options.parameterName"
              :label="select"
              :key="s"
            ></el-checkbox>
          </el-checkbox-group>
        </div>

        <!-- 表格内容 -->
        <div v-for="(head, i) in tableHead" :key="i" class="head-item">
          <span class="head-item-title">{{ head.label }}</span>
          <el-input
            placeholder="请输入内容"
            v-model="searchInput[head.prop]"
            @input="handinput(searchInput[head.prop], head.prop)"
            size="mini"
            clearable
          >
          </el-input>

          <div class="content">
            <div
              v-for="(item, j) in options[head.prop]"
              :key="j"
              class="content-item"
              @click="onRowClick(item)"
            >
              {{ item }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import request from "@/utils/request";
import { getCountryAndPort } from "@/api/stock/whstock.js";
export default {
  props: {
    // 表格头部
    tableHead: {
      type: Array,
      default: () => {
        return [
          {
            label: "国家",
            prop: "country",
          },
          {
            label: "港口",
            prop: "parameterName",
          },
        ];
      },
    },
    tableLists: {
      type: Array,
      default: () => {
        return [
          {
            country: "中国",
            parameterName: "NANSHA",
          },
          {
            country: "中国",
            parameterName: "HUANGPU",
          },
          {
            country: "中国",
            parameterName: "SHEKOU",
          },
          {
            country: "越南",
            parameterName: "YUENAN",
          },
        ];
      },
    },
    // 已选中
    isCheckedList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    /**
     * input框的样式
     */
    inputStyle: {
      type: String,
      default: () => {
        return "";
      },
    },
    tableStyle: {
      type: String,
      default: "",
    },
    isShowSelection: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      value: "",
      allChecked: false, // 是否全选
      searchInput: {}, // 输入内容
      options: [], // 下拉框选项
      oldOptions: [],
      isShowTable: false, // 是否展示表格
      checkList: {}, // 选择框
      tableList: [],

      isIndeterminate: false,
      allChecked: false,
      checkedList: [],
      isIndeterminate: true,
    };
  },
  created() {
    this.getPortList();
    this.searchInput = this.tableHead;
    // this.init();
  },
  watch: {
    tableList: {
      deep: true,
      immediate: true,
      handler(v) {
        this.tableList = v;
        this.init();
      },
    },
    isCheckedList: {
      deep: true,
      handler(v) {
        this.value = this.isCheckedList.toString();
      }
    }
  },
  methods: {
    inEmpty() {
      this.value = '';
    },
    init() {
      this.tableHead.forEach((item) => {
        let arr = [];
        this.tableList.forEach((listItem) => {
          arr.push(listItem[item.prop]);
        });
        this.options[item.prop] = new Set(arr);
        this.oldOptions[item.prop] = new Set(arr);
      });
      this.value = this.isCheckedList.toString();
      this.checkedList = this.isCheckedList;
    },
    // 点击输入框
    deptogglePanel(e) {
      this.isShowTable = !this.isShowTable;
      document.addEventListener("click", this.tableHideList, true);
    },
    // 输入框改变
    onChangeInput() {},
    // 点击行
    onRowClick(row) {
      let country = [...this.options.country];
      if (country.indexOf(row) === -1) {
        this.value = row;
      }
      let obj =
        this.getData(row).length > 0
          ? this.getData(row)[0]
          : {
              code: "",
              country: "",
              id: "",
              parameterName: "",
              parentDictId: "",
              value: "",
            };
      // 传当前对象和value值
      this.$emit("onRowClick", obj, this.value);
      // 如果不是多选
      if (!this.isShowSelection) {
        this.isShowTable = !this.isShowTable;
      }
    },
    // 表格内的输入框改变
    handinput(val, prop) {
      let arr = [];
      for (let item of this.oldOptions[prop].values()) {
        if (item.indexOf(val) !== -1) {
          arr.push(item);
        }
      }
      if (prop === "country") {
        let temp = [];
        for (let i of this.tableList) {
          if (i.country.indexOf(val) !== -1) {
            temp.push(i.parameterName);
          }
        }
        this.options.parameterName = temp;
      }
      this.options[prop] = arr;
    },
    // 选择全部
    handleCheckAllChange(val) {
      this.checkedList = val ? [...this.options.parameterName] : [];
      this.value = this.checkedList.toString();
      this.isIndeterminate = false;
      let arr = [];
      for (let item of this.getData(value)) {
        arr.push(item.value);
      }
      // 传对象数组和value数组
      this.$emit("onSelectRow", this.getData(value), arr);
    },
    // 多选
    handleCheckedPortChange(value) {
      this.value = value.toString();
      let checkedCount = value.length;
      this.allChecked = checkedCount === this.options.parameterName.size;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.options.parameterName.size;
      let arr = [];
      for (let item of this.getData(value)) {
        arr.push(item.value);
      }
      this.$emit("onSelectRow", this.getData(value), arr);
    },
    getData(arr) {
      let array = this.tableList.filter((item) => {
        return arr.includes(item.parameterName);
      });
      return array;
    },
    // 点击别的地方关闭表格
    tableHideList(e) {
      if (
        this.$refs.portTableRef &&
        !this.$refs.portTableRef.contains(e.target)
      ) {
        this.isShowTable = !this.isShowTable;
      }
    },
    getPortList() {
      if (!sessionStorage.getItem("countryAndPort")) {
        // request({
        //   url: "/system/sysparametertype/countryAndPort",
        //   method: "get",
        // })
        getCountryAndPort().then((res) => {
          console.log('港口：', res);
          let arr = [];
          for (let item in res.data) {
            let obj = {};
            res.data[item].forEach((i) => {
              obj = {
                country: item,
                ...i,
              };
              arr.push(obj);
            });
          }
          this.tableList = arr;
          sessionStorage.setItem(
            "countryAndPort",
            JSON.stringify(this.tableList)
          );
        });
      } else {
        this.tableList = JSON.parse(sessionStorage.getItem("countryAndPort"));
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.search-table-style {
  position: relative;
  .search-table {
    position: absolute;
    top: 35px;
    min-width: 300px;
    border: 1px solid #dcdfe6;
    background-color: #fff;
    z-index: 99999;
    .head {
      display: flex;
      &-item {
        display: flex;
        flex-direction: column;
        text-align: center;
        // border-bottom: 1px solid #dcdfe6;
        &-title {
          line-height: 30px;
          border-left: 1px solid #dcdfe6;
        }
      }

      .content {
        .content-item {
          text-align: center;
          height: 24px;
          line-height: 24px;
          border-bottom: 1px solid #dcdfe6;
          border-left: 1px solid #dcdfe6;
          margin-bottom: -1px;
        }
      }

      .select {
        border-right: 1px solid #dcdfe6;
        margin-right: -1px;
        margin-left: 5px;
        box-sizing: border-box;
        .check-group {
          display: flex;
          flex-direction: column;
          margin: 0;
          padding: 0;
          width: 24px;
          margin-top: 23px;
          ::v-deep .el-checkbox {
            height: 24px;
            width: 24px;
            line-height: 24px;
          }
          ::v-deep .el-checkbox__label {
            display: none;
          }
        }
      }
    }
  }
}
</style>
